{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "B8a_URGiowPn"
      },
      "source": [
        "## Overview\n",
        "This colab demonstrates the steps to run a family of DeepLab models built by the DeepLab2 library to perform dense pixel labeling tasks. The models used in this colab perform panoptic segmentation, where the predicted value encodes both semantic class and instance label for every pixel (including both ‘thing’ and ‘stuff’ pixels).\n",
        "\n",
        "### About DeepLab2\n",
        "DeepLab2 is a TensorFlow library for deep labeling, aiming to facilitate future research on dense pixel labeling tasks by providing state-of-the-art and easy-to-use TensorFlow models. Code is made publicly available at https://github.com/google-research/deeplab2\n",
        "\n",
        "The checkpoints used in this demo are pretrained on the Cityscapes dataset."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IGVFjkE2o0K8"
      },
      "source": [
        "### Import and helper methods"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "dQNiIp-LoV6f"
      },
      "outputs": [],
      "source": [
        "import collections\n",
        "import os\n",
        "import tempfile\n",
        "\n",
        "from matplotlib import gridspec\n",
        "from matplotlib import pyplot as plt\n",
        "import numpy as np\n",
        "from PIL import Image\n",
        "import urllib\n",
        "\n",
        "import tensorflow as tf\n",
        "\n",
        "from google.colab import files"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Avk0g2-wo2AO"
      },
      "outputs": [],
      "source": [
        "DatasetInfo = collections.namedtuple(\n",
        "    'DatasetInfo',\n",
        "    'num_classes, label_divisor, thing_list, colormap, class_names')\n",
        "\n",
        "\n",
        "def _cityscapes_label_colormap():\n",
        "  \"\"\"Creates a label colormap used in CITYSCAPES segmentation benchmark.\n",
        "\n",
        "  See more about CITYSCAPES dataset at https://www.cityscapes-dataset.com/\n",
        "  M. Cordts, et al. \"The Cityscapes Dataset for Semantic Urban Scene Understanding.\" CVPR. 2016.\n",
        "\n",
        "  Returns:\n",
        "    A 2-D numpy array with each row being mapped RGB color (in uint8 range).\n",
        "  \"\"\"\n",
        "  colormap = np.zeros((256, 3), dtype=np.uint8)\n",
        "  colormap[0] = [128, 64, 128]\n",
        "  colormap[1] = [244, 35, 232]\n",
        "  colormap[2] = [70, 70, 70]\n",
        "  colormap[3] = [102, 102, 156]\n",
        "  colormap[4] = [190, 153, 153]\n",
        "  colormap[5] = [153, 153, 153]\n",
        "  colormap[6] = [250, 170, 30]\n",
        "  colormap[7] = [220, 220, 0]\n",
        "  colormap[8] = [107, 142, 35]\n",
        "  colormap[9] = [152, 251, 152]\n",
        "  colormap[10] = [70, 130, 180]\n",
        "  colormap[11] = [220, 20, 60]\n",
        "  colormap[12] = [255, 0, 0]\n",
        "  colormap[13] = [0, 0, 142]\n",
        "  colormap[14] = [0, 0, 70]\n",
        "  colormap[15] = [0, 60, 100]\n",
        "  colormap[16] = [0, 80, 100]\n",
        "  colormap[17] = [0, 0, 230]\n",
        "  colormap[18] = [119, 11, 32]\n",
        "  return colormap\n",
        "\n",
        "\n",
        "def _cityscapes_class_names():\n",
        "  return ('road', 'sidewalk', 'building', 'wall', 'fence', 'pole',\n",
        "          'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky',\n",
        "          'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle',\n",
        "          'bicycle')\n",
        "\n",
        "\n",
        "def cityscapes_dataset_information():\n",
        "  return DatasetInfo(\n",
        "      num_classes=19,\n",
        "      label_divisor=1000,\n",
        "      thing_list=tuple(range(11, 19)),\n",
        "      colormap=_cityscapes_label_colormap(),\n",
        "      class_names=_cityscapes_class_names())\n",
        "\n",
        "\n",
        "def perturb_color(color, noise, used_colors, max_trials=50, random_state=None):\n",
        "  \"\"\"Pertrubs the color with some noise.\n",
        "\n",
        "  If `used_colors` is not None, we will return the color that has\n",
        "  not appeared before in it.\n",
        "\n",
        "  Args:\n",
        "    color: A numpy array with three elements [R, G, B].\n",
        "    noise: Integer, specifying the amount of perturbing noise (in uint8 range).\n",
        "    used_colors: A set, used to keep track of used colors.\n",
        "    max_trials: An integer, maximum trials to generate random color.\n",
        "    random_state: An optional np.random.RandomState. If passed, will be used to\n",
        "      generate random numbers.\n",
        "\n",
        "  Returns:\n",
        "    A perturbed color that has not appeared in used_colors.\n",
        "  \"\"\"\n",
        "  if random_state is None:\n",
        "    random_state = np.random\n",
        "\n",
        "  for _ in range(max_trials):\n",
        "    random_color = color + random_state.randint(\n",
        "        low=-noise, high=noise + 1, size=3)\n",
        "    random_color = np.clip(random_color, 0, 255)\n",
        "\n",
        "    if tuple(random_color) not in used_colors:\n",
        "      used_colors.add(tuple(random_color))\n",
        "      return random_color\n",
        "\n",
        "  print('Max trial reached and duplicate color will be used. Please consider '\n",
        "        'increase noise in `perturb_color()`.')\n",
        "  return random_color\n",
        "\n",
        "\n",
        "def color_panoptic_map(panoptic_prediction, dataset_info, perturb_noise):\n",
        "  \"\"\"Helper method to colorize output panoptic map.\n",
        "\n",
        "  Args:\n",
        "    panoptic_prediction: A 2D numpy array, panoptic prediction from deeplab\n",
        "      model.\n",
        "    dataset_info: A DatasetInfo object, dataset associated to the model.\n",
        "    perturb_noise: Integer, the amount of noise (in uint8 range) added to each\n",
        "      instance of the same semantic class.\n",
        "\n",
        "  Returns:\n",
        "    colored_panoptic_map: A 3D numpy array with last dimension of 3, colored\n",
        "      panoptic prediction map.\n",
        "    used_colors: A dictionary mapping semantic_ids to a set of colors used\n",
        "      in `colored_panoptic_map`.\n",
        "  \"\"\"\n",
        "  if panoptic_prediction.ndim != 2:\n",
        "    raise ValueError('Expect 2-D panoptic prediction. Got {}'.format(\n",
        "        panoptic_prediction.shape))\n",
        "\n",
        "  semantic_map = panoptic_prediction // dataset_info.label_divisor\n",
        "  instance_map = panoptic_prediction % dataset_info.label_divisor\n",
        "  height, width = panoptic_prediction.shape\n",
        "  colored_panoptic_map = np.zeros((height, width, 3), dtype=np.uint8)\n",
        "\n",
        "  used_colors = collections.defaultdict(set)\n",
        "  # Use a fixed seed to reproduce the same visualization.\n",
        "  random_state = np.random.RandomState(0)\n",
        "\n",
        "  unique_semantic_ids = np.unique(semantic_map)\n",
        "  for semantic_id in unique_semantic_ids:\n",
        "    semantic_mask = semantic_map == semantic_id\n",
        "    if semantic_id in dataset_info.thing_list:\n",
        "      # For `thing` class, we will add a small amount of random noise to its\n",
        "      # correspondingly predefined semantic segmentation colormap.\n",
        "      unique_instance_ids = np.unique(instance_map[semantic_mask])\n",
        "      for instance_id in unique_instance_ids:\n",
        "        instance_mask = np.logical_and(semantic_mask,\n",
        "                                       instance_map == instance_id)\n",
        "        random_color = perturb_color(\n",
        "            dataset_info.colormap[semantic_id],\n",
        "            perturb_noise,\n",
        "            used_colors[semantic_id],\n",
        "            random_state=random_state)\n",
        "        colored_panoptic_map[instance_mask] = random_color\n",
        "    else:\n",
        "      # For `stuff` class, we use the defined semantic color.\n",
        "      colored_panoptic_map[semantic_mask] = dataset_info.colormap[semantic_id]\n",
        "      used_colors[semantic_id].add(tuple(dataset_info.colormap[semantic_id]))\n",
        "  return colored_panoptic_map, used_colors\n",
        "\n",
        "\n",
        "def vis_segmentation(image,\n",
        "                     panoptic_prediction,\n",
        "                     dataset_info,\n",
        "                     perturb_noise=60):\n",
        "  \"\"\"Visualizes input image, segmentation map and overlay view.\"\"\"\n",
        "  plt.figure(figsize=(30, 20))\n",
        "  grid_spec = gridspec.GridSpec(2, 2)\n",
        "\n",
        "  ax = plt.subplot(grid_spec[0])\n",
        "  plt.imshow(image)\n",
        "  plt.axis('off')\n",
        "  ax.set_title('input image', fontsize=20)\n",
        "\n",
        "  ax = plt.subplot(grid_spec[1])\n",
        "  panoptic_map, used_colors = color_panoptic_map(panoptic_prediction,\n",
        "                                                 dataset_info, perturb_noise)\n",
        "  plt.imshow(panoptic_map)\n",
        "  plt.axis('off')\n",
        "  ax.set_title('panoptic map', fontsize=20)\n",
        "\n",
        "  ax = plt.subplot(grid_spec[2])\n",
        "  plt.imshow(image)\n",
        "  plt.imshow(panoptic_map, alpha=0.7)\n",
        "  plt.axis('off')\n",
        "  ax.set_title('panoptic overlay', fontsize=20)\n",
        "\n",
        "  ax = plt.subplot(grid_spec[3])\n",
        "  max_num_instances = max(len(color) for color in used_colors.values())\n",
        "  # RGBA image as legend.\n",
        "  legend = np.zeros((len(used_colors), max_num_instances, 4), dtype=np.uint8)\n",
        "  class_names = []\n",
        "  for i, semantic_id in enumerate(sorted(used_colors)):\n",
        "    legend[i, :len(used_colors[semantic_id]), :3] = np.array(\n",
        "        list(used_colors[semantic_id]))\n",
        "    legend[i, :len(used_colors[semantic_id]), 3] = 255\n",
        "    if semantic_id \u003c dataset_info.num_classes:\n",
        "      class_names.append(dataset_info.class_names[semantic_id])\n",
        "    else:\n",
        "      class_names.append('ignore')\n",
        "\n",
        "  plt.imshow(legend, interpolation='nearest')\n",
        "  ax.yaxis.tick_left()\n",
        "  plt.yticks(range(len(legend)), class_names, fontsize=15)\n",
        "  plt.xticks([], [])\n",
        "  ax.tick_params(width=0.0, grid_linewidth=0.0)\n",
        "  plt.grid('off')\n",
        "  plt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1ly6p6M2o8SF"
      },
      "source": [
        "### Select a pretrained model"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "peo7LUTtulpQ"
      },
      "outputs": [],
      "source": [
        "MODEL_NAME = 'resnet50_kmax_deeplab_cityscapes_train'  # @param ['resnet50_os32_panoptic_deeplab_cityscapes_crowd_trainfine_saved_model', 'resnet50_beta_os32_panoptic_deeplab_cityscapes_trainfine_saved_model', 'wide_resnet41_os16_panoptic_deeplab_cityscapes_trainfine_saved_model', 'swidernet_sac_1_1_1_os16_panoptic_deeplab_cityscapes_trainfine_saved_model', 'swidernet_sac_1_1_3_os16_panoptic_deeplab_cityscapes_trainfine_saved_model', 'swidernet_sac_1_1_4.5_os16_panoptic_deeplab_cityscapes_trainfine_saved_model', 'axial_swidernet_1_1_1_os16_axial_deeplab_cityscapes_trainfine_saved_model', 'axial_swidernet_1_1_3_os16_axial_deeplab_cityscapes_trainfine_saved_model', 'axial_swidernet_1_1_4.5_os16_axial_deeplab_cityscapes_trainfine_saved_model', 'max_deeplab_s_backbone_os16_axial_deeplab_cityscapes_trainfine_saved_model', 'max_deeplab_l_backbone_os16_axial_deeplab_cityscapes_trainfine_saved_model', 'resnet50_kmax_deeplab_cityscapes_train','axial_resnet50_kmax_deeplab_cityscapes_train','convnext_tiny_kmax_deeplab_cityscapes_train','convnext_small_kmax_deeplab_cityscapes_train','convnext_base_kmax_deeplab_cityscapes_train','convnext_large_kmax_deeplab_cityscapes_train']\n",
        "\n",
        "\n",
        "_MODELS = ('resnet50_os32_panoptic_deeplab_cityscapes_crowd_trainfine_saved_model',\n",
        "           'resnet50_beta_os32_panoptic_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'wide_resnet41_os16_panoptic_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'swidernet_sac_1_1_1_os16_panoptic_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'swidernet_sac_1_1_3_os16_panoptic_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'swidernet_sac_1_1_4.5_os16_panoptic_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'axial_swidernet_1_1_1_os16_axial_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'axial_swidernet_1_1_3_os16_axial_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'axial_swidernet_1_1_4.5_os16_axial_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'max_deeplab_s_backbone_os16_axial_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'max_deeplab_l_backbone_os16_axial_deeplab_cityscapes_trainfine_saved_model',\n",
        "           'resnet50_kmax_deeplab_cityscapes_train',\n",
        "           'axial_resnet50_kmax_deeplab_cityscapes_train',\n",
        "           'convnext_tiny_kmax_deeplab_cityscapes_train',\n",
        "           'convnext_small_kmax_deeplab_cityscapes_train',\n",
        "           'convnext_base_kmax_deeplab_cityscapes_train',\n",
        "           'convnext_large_kmax_deeplab_cityscapes_train',)\n",
        "_DOWNLOAD_URL_PATTERN = 'https://storage.googleapis.com/gresearch/tf-deeplab/saved_model/%s.tar.gz'\n",
        "\n",
        "_MODEL_NAME_TO_URL_AND_DATASET = {\n",
        "    model: (_DOWNLOAD_URL_PATTERN % model, cityscapes_dataset_information())\n",
        "    for model in _MODELS\n",
        "}\n",
        "\n",
        "MODEL_URL, DATASET_INFO = _MODEL_NAME_TO_URL_AND_DATASET[MODEL_NAME]\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UjYwP1Sjo4dd"
      },
      "outputs": [],
      "source": [
        "model_dir = tempfile.mkdtemp()\n",
        "\n",
        "download_path = os.path.join(model_dir, MODEL_NAME + '.gz')\n",
        "urllib.request.urlretrieve(MODEL_URL, download_path)\n",
        "\n",
        "!tar -xzvf {download_path} -C {model_dir}\n",
        "\n",
        "LOADED_MODEL = tf.saved_model.load(os.path.join(model_dir, MODEL_NAME))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "umpwnn4etG6z"
      },
      "source": [
        "### Run on sample images"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6552FXlAOHnX"
      },
      "outputs": [],
      "source": [
        "# Required, upload an image from your local machine.\n",
        "\n",
        "uploaded = files.upload()\n",
        "\n",
        "if not uploaded:\n",
        "  raise AssertionError('Please upload one image')\n",
        "elif len(uploaded) == 1:\n",
        "  UPLOADED_FILE = list(uploaded.keys())[0]\n",
        "else:\n",
        "  raise AssertionError('Please upload one image at a time')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bsQ7Oj7jtHDz"
      },
      "outputs": [],
      "source": [
        "with tf.io.gfile.GFile(UPLOADED_FILE, 'rb') as f:\n",
        "  im = np.array(Image.open(f))\n",
        "\n",
        "output = LOADED_MODEL(tf.cast(im, tf.uint8))\n",
        "vis_segmentation(im, output['panoptic_pred'][0], DATASET_INFO)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "k2-EDpBCwmpq"
      },
      "outputs": [],
      "source": [
        ""
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "DeepLab_Cityscapes_Demo.ipynb",
      "private_outputs": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
